/**
 * 
 */
package com.gmail.blackdog1987.carcare.activity;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Camera.ErrorCallback;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gmail.blackdog1987.carcare.BaseActivity;
import com.gmail.blackdog1987.carcare.R;
import com.gmail.blackdog1987.carcare.db.dao.UserDao;
import com.gmail.blackdog1987.carcare.network.request.builder.GetCodeRequestBuilder;
import com.gmail.blackdog1987.carcare.network.request.builder.RegRequestBuilder;
import com.gmail.blackdog1987.carcare.network.response.IResponse;
import com.gmail.blackdog1987.carcare.network.response.RegResponse;
import com.gmail.blackdog1987.carcare.network.response.handler.IResponseHandler;
import com.gmail.blackdog1987.carcare.network.response.handler.OnResponseListener;
import com.gmail.blackdog1987.carcare.network.response.handler.RegResponseHandler;
import com.gmail.blackdog1987.carcare.util.ErrorCode;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * @author wdy
 *
 */
public class RegActivity extends BaseActivity implements OnResponseListener, OnClickListener {
	private Context mContext;
	private static final String TAG = RegActivity.class.getSimpleName();
	private EditText mId;
	private EditText mPwd;
	private EditText mPwd2;
	private EditText mCode;
	private TextView mGetCode;

	private RegRequestBuilder mReq = new RegRequestBuilder();
	private RegResponseHandler mHandler = new RegResponseHandler();
	private GetCodeRequestBuilder mGetCodeReq = new GetCodeRequestBuilder();

	public String username;
	public String pwd;
	public EditText cartype;
	public EditText carnumber;
	public EditText enginenumber;
	public EditText carbonenumber;
	public TextView baoyang;
	public TextView nianjian;

	int count = 60;
	private TimerTask timerTask;
	private Timer timer;

	private AlertDialog mExInputDialog;
	private static final int TIME_ADD = 1;
	private static final int TIME_RESET = 2;
	private Handler mMsgHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case TIME_ADD:
				mGetCode.setText("" + count);
				break;
			case TIME_RESET:
				mGetCode.setText("重新获取");
				mGetCode.setOnClickListener(RegActivity.this);
				mGetCode.setBackgroundResource(R.color.blue);
				timer.cancel();
				break;
			default:
				break;
			}
		};
	};

	public void startCount() {
		if(timer!=null&&timerTask!=null){
			timer = new Timer();
			timerTask = new TimerTask() {
				@Override
				public void run() {
					if (count > 0) {
						mMsgHandler.sendEmptyMessage(TIME_ADD);
					} else {
						mMsgHandler.sendEmptyMessage(TIME_RESET);
					}
					count--;

				}
			};
			timer.schedule(timerTask, 0, 1000);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reg);

		mContext = this;
		initViews();
		reg();
		timer = new Timer();
		timerTask = new TimerTask() {
			@Override
			public void run() {
				if (count > 0) {
					mMsgHandler.sendEmptyMessage(TIME_ADD);
				} else {
					mMsgHandler.sendEmptyMessage(TIME_RESET);
				}
				count--;

			}
		};
	}

	@Override
	public void initViews() {
		super.initViews();
		mId = (EditText) findViewById(R.id.reg_id);
		mPwd = (EditText) findViewById(R.id.reg_pwd);
		mPwd2 = (EditText) findViewById(R.id.reg_pwd2);
		mCode = (EditText) findViewById(R.id.reg_code);
		mGetCode = (TextView) findViewById(R.id.reg_getcode);
		cartype = (EditText) findViewById(R.id.reg_cartype);
		carnumber = (EditText) findViewById(R.id.reg_carnumber);
		enginenumber = (EditText) findViewById(R.id.reg_enginenumber);
		carbonenumber = (EditText) findViewById(R.id.reg_carbonenumber);

		mExInputDialog = new AlertDialog.Builder(mContext).setMessage("完善所有资料我们将通过短信向您发放［洗车卷］，是否继续填写？")
				.setNegativeButton("直接注册", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						post();
						dialog.dismiss();
					}
				}).setPositiveButton("继续填写", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).setTitle("温馨提示").create();
	}

	@Override
	public void reg() {
		super.reg();
		findViewById(R.id.reg_ok).setOnClickListener(this);
		findViewById(R.id.back).setOnClickListener(this);
		mHandler.setOnResponseListener(this);
		mGetCode.setOnClickListener(this);
	}

	@Override
	public void initData() {
		super.initData();
	}

	@Override
	public void onResponse(IResponseHandler classz) {
		if (((RegResponse) classz.getResponse()).user != null) {
			new UserDao().saveUser(((RegResponse) classz.getResponse()).user);
			Toast.makeText(mContext, "注册成功！", Toast.LENGTH_LONG).show();
			setResult(Activity.RESULT_OK);
			finish();
		}
	}

	@Override
	public void onError(IResponseHandler classz) {
		IResponse res = classz.getResponse();
		if(res instanceof RegResponse){
			if(((RegResponse) res).error.getMessage().equals(ErrorCode.REG_EXISTS)){
				Toast.makeText(mContext, "该电话已经被注册！", Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(mContext, "注册失败！", Toast.LENGTH_LONG).show();
			}
		}
	}

	private boolean validExInput() {
		if (cartype.getText().toString().length() == 0 || carnumber.getText().toString().length() == 0 || enginenumber.getText().toString().length() == 0
				|| carbonenumber.getText().toString().length() == 0) {
			mExInputDialog.show();
			return false;
		}
		return true;
	}

	private boolean validInput() {
		if (!mId.getText().toString().matches("^1[34578]\\d{9}$")) {
			Toast.makeText(mContext, "请输入正确得手机号码", Toast.LENGTH_LONG).show();
			return false;
		}
		if (mPwd.getText().toString().length() == 0) {
			Toast.makeText(mContext, "密码不能为空", Toast.LENGTH_LONG).show();
			return false;
		}
		if (!mPwd.getText().toString().equals(mPwd2.getText().toString())) {
			Toast.makeText(mContext, "两次密码不一致", Toast.LENGTH_LONG).show();
			return false;
		}
		if (mCode.getText().toString().trim().length()==0) {
			Toast.makeText(mContext, "验证码不能为空", Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}

	private void post() {
		mReq.setUsername(mId.getText().toString()).setPwd(mPwd.getText().toString()).setCarbonenumber(carbonenumber.getText().toString().trim())
				.setCarnumber(carnumber.getText().toString().trim()).setCartype(cartype.getText().toString()).setCode(mCode.getText().toString().trim())
				.setEnginenumber(enginenumber.getText().toString()).postJsonRequest(mContext, mHandler);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.reg_getcode:
			count = 60;
			startCount();
			mGetCodeReq.setMobile(mId.getText().toString().trim());
			mGetCodeReq.postJsonRequest(mContext, new AsyncHttpResponseHandler());
			mGetCode.setOnClickListener(null);
			mGetCode.setBackgroundResource(R.color.bg_grey);
			break;
		case R.id.reg_ok:
			if (validInput() && validExInput()) {
				post();
			}
			break;
		case R.id.back:
			finish();
			break;
		}
	}
}
